# 用于解析请求的参数
import re
from django.utils.deprecation import MiddlewareMixin

from ExtraXueHomepage import settings
from ExtraXueHomepage.settings import LoggerConfig as log

# 日志
from Main import models
from Main.utils import timeUtil

logger = log().mylogger_basic()
logger.getLogger(__name__)


class RequestAnalysisMiddleware(MiddlewareMixin):

    def process_request(self, request):

        if request.META.get("HTTP_X_FORWARDED_FOR"):
            remote_addr = request.META.get("HTTP_X_FORWARDED_FOR")
        else:
            remote_addr = request.META.get("REMOTE_ADDR")

        request_path = request.META.get("PATH_INFO")

        request_re_filter = settings.REQUEST_RE_FILTER

        if remote_addr != "127.0.0.1" and not re.findall(request_re_filter,request_path) and request_path != "/":

            access_instance = models.AccessLog()

            access_instance.access_ip_addr = remote_addr
            access_instance.access_path = request_path
            access_instance.access_time = timeUtil.get_now_time()
            access_instance.save()

            logger.info("Remote Address is %s , Request Path is %s ", remote_addr, request_path)
